package com.reger.gateway.service.impl;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.RoutesRefreshedEvent;
import org.springframework.cloud.netflix.zuul.filters.CompositeRouteLocator;
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties.ZuulRoute;
import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import com.reger.gateway.service.ZuulRefreshService;

@Service
public class ZuulRefreshServiceImpl implements ZuulRefreshService {

	private static final Logger log = LoggerFactory.getLogger(ZuulRefreshServiceImpl.class);

	@Autowired
	private ZuulProperties properties;
	@Autowired
	private ApplicationEventPublisher publisher;
	@Autowired
	private CompositeRouteLocator routeLocator;
	@Autowired
	private DiscoveryClientRouteLocator discoveryRouteLocator;
//	@Autowired
//	private JdbcTemplate jdbcTemplate;

	@Override
	public Map<String, ZuulRoute> refreshRoute() {
		log.info("开始刷新路由信息...");
		Map<String, ZuulRoute> routes = properties.getRoutes();
		routes.clear();
		ZuulRoute route = new ZuulRoute("test", "baidu", "https://www.baidu.com", "", false, true, null);
		routes.put(route.getId(), route);
		routeLocator.refresh();
		this.publishEvent();
		return routes;
	}
	
	private void publishEvent() {
		RoutesRefreshedEvent routesRefreshedEvent = new RoutesRefreshedEvent(routeLocator);
		publisher.publishEvent(routesRefreshedEvent);
	}
	
	@Override
	public List<Route> watchRoute() {
		List<Route> routes = discoveryRouteLocator.getRoutes();
		return routes;
	}
}
